package cn.botter.subject.domain.service.impl;

import cn.botter.subject.common.enums.IsDeletedEnum;
import cn.botter.subject.domain.convert.SubjectCategoryConverter;
import cn.botter.subject.domain.entity.SubjectCategoryBO;
import cn.botter.subject.domain.entity.SubjectLabelBO;
import cn.botter.subject.domain.service.SubjectDomainCategoryService;
import cn.botter.subject.domain.utils.LocalCacheUtil;
import cn.botter.subject.infra.basic.entity.SubjectCategory;
import cn.botter.subject.infra.basic.entity.SubjectLabel;
import cn.botter.subject.infra.basic.entity.SubjectMapping;
import cn.botter.subject.infra.basic.service.SubjectCategoryService;
import cn.botter.subject.infra.basic.service.SubjectLabelService;
import cn.botter.subject.infra.basic.service.SubjectMappingService;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class SubjectDomainCategoryServiceImpl implements SubjectDomainCategoryService {

    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private LocalCacheUtil localCacheUtil;
    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));

        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        System.out.println(subjectCategory);
        subjectCategory.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        SubjectCategory category = subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> bolist = SubjectCategoryConverter.INSTANCE
                .convertBoToCategoryList(subjectCategoryList);
        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.queryPrimaryCategory.bolist:{}", JSON.toJSONString(bolist));
        }
        bolist.forEach(bo->{
            Integer count = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(count);
        });
        return bolist;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.update.boolean:{}", JSON.toJSONString(count));
        }
        return count>0;
    }

    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);

        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.delete.boolean:{}", JSON.toJSONString(count));
        }
        return count > 0;
    }


    /**
     * 查询分类以及标签
     * @param subjectCategoryBO
     * @return
     */
    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        String cacheKey = "categoryAndLabel."+subjectCategoryBO.getId();
        Integer id = subjectCategoryBO.getId();
        List<SubjectCategoryBO> result = localCacheUtil.getResult(cacheKey, SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(id));
        return result;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Integer categoryId) {
        //查询当前大类下的所有分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);

        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.queryPrimaryCategory.bolist:{}", JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> subjectCategoryBOS = SubjectCategoryConverter.INSTANCE.convertBoToCategoryList(subjectCategoryList);

//        return getSubjectCategoryBOS(subjectCategoryBOS);

        //使用CompletableFuture实现多线程的开发
        Stream<CompletableFuture<Map<Integer, List<SubjectLabelBO>>>> completableFutureStream = subjectCategoryBOS.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getSubjectLabelBOList(category), threadPoolExecutor));
        Map<Integer, List<SubjectLabelBO>> map = new HashMap<>();
        completableFutureStream.forEach(future -> {
            try {
                Map<Integer, List<SubjectLabelBO>> result = future.get();
                if (!CollectionUtils.isEmpty(result)) {
                    map.putAll(result);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        subjectCategoryBOS.forEach(category -> {
            List<SubjectLabelBO> labelBOList = map.get(category.getId());
            if (!CollectionUtils.isEmpty(labelBOList)) {
                category.setLabelBOList(labelBOList);
            }
        });
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOSByFutureTask(List<SubjectCategoryBO> subjectCategoryBOS)
                                    throws InterruptedException, ExecutionException {
        //使用FutureTask实现多并发
        List<FutureTask<Map<Integer , List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>(); //将任务同意处理后，做遍历
        subjectCategoryBOS.forEach(category -> {
            FutureTask<Map<Integer , List<SubjectLabelBO>>> futureTask = new FutureTask<>(()->getSubjectLabelBOList(category));
            futureTaskList.add(futureTask);
            //向线程池提交
            threadPoolExecutor.submit(futureTask);
        });
        Map<Integer, List<SubjectLabelBO>> map = new HashMap<>();
        for (FutureTask<Map<Integer, List<SubjectLabelBO>>> mapFutureTask : futureTaskList) {
            Map<Integer, List<SubjectLabelBO>> labelMap = mapFutureTask.get();
            if (CollectionUtils.isEmpty(labelMap)){
                continue;
            }
            map.putAll(labelMap);
        }
        subjectCategoryBOS.forEach(category -> {
            category.setLabelBOList(map.get(category.getId()));
        });
        return subjectCategoryBOS;
    }

    private Map<Integer , List<SubjectLabelBO>> getSubjectLabelBOList(SubjectCategoryBO category) {
        Map<Integer , List<SubjectLabelBO>> labelMap = new HashMap<>();

        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappings)){
            return null;
        }
        List<Integer> labelIdList = subjectMappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList = new LinkedList<>();
        subjectLabelList.forEach(label -> {
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setCategoryId(label.getCategoryId());
            subjectLabelBO.setId(label.getId());
            subjectLabelBO.setLabelName(label.getLabelName());
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(), labelBOList);
        return labelMap;
    }

}
